﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Windows.Forms;
using Sunlight.Dispatch.Dal;
using Sunlight.Dispatch.Tools;
using Sunlight.Dispatch.UI.Controls;
using Sunlight.Dispatch.UI.Extensions;

namespace Sunlight.Dispatch.UI.TimeGranlarityForms {
    public partial class SettingByWeekFrm : BaseEditFrm {
        public SettingByWeekFrm() {
            InitializeComponent();
            this.Load += SettingByDayFrm_Load;
        }

        private void SettingByDayFrm_Load(object sender, EventArgs e) {
            this.dataGridView.AutoGenerateColumns = false;
            this.Register.RegisterNumber(new[] { this.textBoxFrequency });
            this.OnControlCreated(this.dataGridView, null);
            this.dataGridView.RowPostPaint += this.DataGridView_RowPostPaint;
            this.dataGridView.SelectionChanged += this.DataGridView_SelectionChanged;
        }

        //编辑时调用此方法,用户初始化界面显示
        public void SetObjectToEdit(string intfCode, string connectString) {
            this.dataGridView.Cursor = Cursors.WaitCursor;
            string msg;
            if(!Utils.IsCanConnect(out msg, connectString)) {
                MessageBoxEx.Show(this, msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            using(var context = new MonitorSettingDataContext(connectString)) {
                var source = context.TRule.Include("TRuleList").FirstOrDefault(data => data.ParentCode == intfCode);
                if(source == null) {
                    MessageBoxEx.Show(this, "当前实体不存在，请检查", "错误");
                    return;
                }
            }
            this.dateTimePickerBeginTime.Cursor = Cursors.Default;
        }

        public override void SetObjectToEditById(object identity, string connectString) {
            this.InitChecked();
            this.dataGridView.Cursor = Cursors.WaitCursor;
            using(var context = new MonitorSettingDataContext(connectString)) {
                var source = context.TRule.Include("TRuleList").FirstOrDefault(data => data.ParentCode == identity.ToString());
                if(source == null) {
                    MessageBoxEx.Show(this, "当前实体不存在，请检查", "错误");
                    return;
                }

                this.SetObjectToEdit(source);
                if(!string.IsNullOrEmpty(source.MonthDay)) {
                    var months = source.WeekDay.Split(',');
                    foreach(var month in months) {
                        var control = CheckBoxsForWeek().FirstOrDefault(data => data.Name == $"chk{month}");
                        if(control != null)
                            control.Checked = true;
                    }
                }

                this.dataGridView.ClearDataSource();
                this.dataGridView.DataSource = source.TRuleList;
            }
            this.dataGridView.Cursor = Cursors.Default;
        }

        private void InitChecked() {
            CheckBoxsForWeek().ForEach(data => data.Checked = false);
        }

        private List<CheckBox> CheckBoxsForWeek() {
            var checkBoxs = new List<CheckBox>();
            foreach(var control in this.panelContainer.Controls) {
                var checkBox = control as CheckBox;
                if(checkBox != null) {
                    checkBoxs.Add(checkBox);
                }
            }

            return checkBoxs;
        }

        private void tsbSave_Click(object sender, EventArgs e) {
            var dataContext = this.DataContext as TRule;
            if(dataContext == null)
                return;
            if(string.IsNullOrEmpty(this.textBoxFrequency.Text) || Convert.ToInt32(this.textBoxFrequency.Text) <= 1) {
                MessageBoxEx.Show(this, "频率不能为空，且不能小于1", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            if(!dataContext.TRuleList.Any()) {
                MessageBoxEx.Show(this, "时间区间清单不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if(CheckBoxsForWeek().All(data => !data.Checked)) {
                MessageBoxEx.Show(this, "请选择执行周", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var weekDay = CheckBoxsForWeek().Where(data => data.Checked).Select(data => data.Tag.ToString().PadLeft(2, '0')).OrderBy(data => data).ToArray();
            dataContext.WeekDay = string.Join(",", weekDay);
            dataContext.Frequency = Convert.ToInt32(this.textBoxFrequency.Text);
            dataContext.ExecutionTime = DateTime.Now;
            dataContext.Kind = (int)TimeGranlarity.周;
            dataContext.blnUp = (int)YesOrNo.是;//TODO:待确定是何作用

            this.RasieExtendEvent(dataContext);
            //TODO :保存时，将保存内容传入外部，保证能被公用
            //var context = new MonitorSettingDataContext();
            //context.TRule.InsertOnSubmit(rule);
            //context.SubmitChanges();
        }

        private void btnAddRuleList_Click(object sender, EventArgs e) {
            var rule = this.DataContext as TRule;
            if(rule == null || rule.TRuleList == null)
                return;
            //TODO：必须判断再次添加的开始时间必须大于已经添加的任意结束时间
            var ruleList = new TRuleList();
            ruleList.TRule = rule;
            ruleList.StartTime = this.dateTimePickerBeginTime.Value.ToString("HH:mm");
            rule.TRuleList.Add(ruleList);
            this.dataGridView.ClearDataSource();
            //dataGridView不支持EntitySet集合，必须ToList()
            this.dataGridView.DataSource = rule.TRuleList.ToList();
        }

        private void btnDelete_Click(object sender, EventArgs e) {
            var rule = this.DataContext as TRule;
            if(rule == null || this.dataGridView.SelectedRows.Count <= 0)
                return;
            var item = this.dataGridView.SelectedRows.Cast<DataGridViewRow>().Select(d => d.DataBoundItem)
                .Cast<TRuleList>().FirstOrDefault();
            if(item == null)
                return;
            rule.TRuleList.Remove(item);
            this.dataGridView.ClearDataSource();
            this.dataGridView.DataSource = rule.TRuleList.ToList();
        }

        private void toolStripButtonExit_Click(object sender, EventArgs e) {
            if(MessageBoxEx.Show("是否退出该界面，请确认？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK) {
                this.Close();
            }
        }
    }
}
